package com.jkm.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;


@Configuration
@AutoConfigureAfter(DataSourceConfig.class)
@MapperScan(basePackages={"com.jkm.mapper.read"},sqlSessionFactoryRef="sqlSessionFactorySlave")
public class ReadDataSourceConfig {

    @Bean(name = "sqlSessionFactorySlave")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("slave")DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        factory.setTypeAliasesPackage("com.jkm.model");
        System.out.println("加载slave=============================================================");
//        DataSourceInterceptor dataSourceInterceptor = new DataSourceInterceptor();
//        factory.setPlugins(new Interceptor[]{dataSourceInterceptor});
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            factory.setMapperLocations(resolver.getResources("classpath:com.jkm.mapper.write/*.xml"));
            return factory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
